// subpages/Generalreservationfillorder/Generalreservationdetailfillorder.js
var app = getApp()
Page({
  data: {
    date: "选择日期",
    time: "选择时间",
    address: "点击选择所在区域",
    buybuttonText: '购买',
    editDisable: false,
    // startTime: '',
    startDate: '',
    note:'',
    remarkExtra:'',
    orderstatus:''
  },
  onLoad: function (e) {
    var that = this;
    if(e&&e.id){
      that.setData({
        gid: e.id
      })
    }
    if (e && e.num){
      that.setData({
        num: e.num
      })
    }
    if (e && e.gfid) {
      that.setData({
        gfid: e.gfid
      })
    }
    var date = new Date();
    var year = date.getFullYear()
    var month = date.getMonth() + 1
    var day = date.getDate()

    var hour = date.getHours()
    var minute = date.getMinutes()
    var second = date.getSeconds()

    var subDate = year.toString() + "-" + month.toString() + "-" + day.toString()
    var subTime = hour.toString() + ":" + minute.toString()
    that.setData({
      startDate: subDate,
      // startTime: subTime
    })
    console.log(that.data.startDate)
    if (!app.globalData.plumSession) {
      app.wechatSq(that);
      setTimeout(function () {
        that.loadData();
      }, 1000)
    } else {
      that.loadData();
    }
  },
  onShow:function(){
    var that = this;
    if (!app.globalData.plumSession) {
      app.wechatSq(that);
    } else {
      that.requestpayType();
    }
  },
  requestpayType: function () {
    var that = this;
    wx.showLoading({
      title: '正在加载',
      mask: true,
      time: 100000
    })
    wx.request({
      url: app.globalData.requestUrl,
      data: {
        map: 'applet_pay_cfg'
      },
      success: function (res) {
        console.log(res.data);
        if (res.data.ec == 200) {
          that.setData({
            payType: res.data.data,
            payWay: res.data.data ? res.data.data[0].type : 1
          })
        } else {
          console.log(res.data)
          that.setData({
            payType: []
          })
        }
      },
      complete: function () {
        wx.hideLoading();
      }
    });
  },
  toRecharge: function () {
    wx.navigateTo({
      url: '/subpages/walletRecharge/walletRecharge',
    })
  },
  payRadioChange: function (e) {
    this.setData({
      payWay: e.detail.value
    })
    console.log(this.data.payWay);
  },
  loadData: function () {
    var that = this;
    wx.showLoading({
      title: '加载中...',
    })
    wx.request({
      url: app.globalData.requestUrl,
      data: {
        map: 'applet_appointment_create_trade',
        buys: JSON.stringify([{ "gid": that.data.gid, "num": that.data.num, "gfid": that.data.gfid }])
      },
      success: function (res) {
        console.log(res.data)
        if (res.data.ec == 200) {
          if (!that.data.remarkExtra) {
            var remarkExtra = res.data.data.remarkExtra;
            if (remarkExtra) {
              for (var i = 0; i < remarkExtra.length; i++) {
                remarkExtra[i].id = i;
                remarkExtra[i].value = '';
              }
              that.setData({
                remarkExtra: remarkExtra
              })
            } else {
              that.setData({
                remarkExtra: []
              })
            }
          }
          that.setData({
            info: res.data.data
          })
        } else {
          app.errorTip(that, res.data.em, 2000);
        }
      },
      fail: function () {
        console.log("fail")
      },
      complete: function () {
        wx.hideLoading()
      }
    })
  },
  //日期选择
  bindDateChange: function (e) {
    var that = this;
    that.setData({
      date: e.detail.value
    })
  },
  //时间选择
  bindTimeChange: function (e) {
    var that = this;
    that.setData({
      time: e.detail.value
    })
  },
  //选择地区
  chooseArea: function () {
    var that = this;
    if (that.data.editDisable == true) {
      return;
    }
    wx.chooseLocation({
      success: function (res) {
        console.log(res)
        that.setData({
          address: res.name
        })
      },
    })
  },
  //姓名输入
  nameChanged: function (e) {
    var that = this;
    that.setData({
      username: e.detail.value
    })
  },
  //电话输入
  phoneChanged: function (e) {
    console.log(e.detail.value)
    var that = this;
    that.setData({
      userphone: e.detail.value
    })
  },
  //地址输入
  addressChanged: function (e) {
    var that = this;
    that.setData({
      detailAddress: e.detail.value
    })
  },
  //备注输入
  noteChanged: function (e) {
    var that = this;
    that.setData({
      note: e.detail.value
    })
  },
  buyClick: function () {
    var that = this;
    app.getSubId(that, 'applet_appointment_create_order', 'toBuyClick');
  },
  //购买按钮点击
  toBuyClick: function () {
    var that = this;
    if (that.data.buybuttonText != '购买') {
      that.payment();
      return;
    }
    
    console.log(that.data)
    var data = {
      map: 'applet_appointment_create_order',
      tid: that.data.info.trade.tid,
      payType :that.data.payWay,
      note: that.data.note,
      name: that.data.username,
      phone: that.data.userphone,
      address: that.data.address + that.data.detailAddress,
      time: that.data.date + " " + that.data.time
    }
    var remarkExtra = that.data.remarkExtra;
    for (var i = 0; i < remarkExtra.length; i++) {
      if (remarkExtra[i].require) {
        if (!remarkExtra[i].value) {
          if (remarkExtra[i].type == 'time' && remarkExtra[i].date) {
            remarkExtra[i].value = remarkExtra[i].dateval + ' ' + remarkExtra[i].timeval;
          }
          if (remarkExtra[i].type == 'time') {
            if (!remarkExtra[i].dateval) {
              app.errorTip(that, '请选择' + remarkExtra[i].name + '的日期', 2000);
              return;
            }
            if (!remarkExtra[i].timeval) {
              app.errorTip(that, '请选择' + remarkExtra[i].name + '的时间', 2000);
              return;
            }
          } else {
            app.errorTip(that, remarkExtra[i].name + '为必填项', 2000);
            return;
          }
        }
      }
    }
    data.remarkExtra = that.data.remarkExtra;
    console.log(data.remarkExtra);
    console.log(data);
    console.log(app.globalData.requestUrl);
    wx.showLoading({
      title: '加载中',
    })
    wx.request({
      url: app.globalData.requestUrl,
      data: data,
      success: function (res) {
        console.log(res)
        if (res.data.ec == 200) {
          that.setData({
            editDisable: true,
            buybuttonText: "支付",
            orderstatus: res.data.data.status
          })
          if (res.data.data.status == 'dzf') {
            if (data.payType==1){
              that.payment();
            }else{
              wx.redirectTo({
                url: '/subpages/Generalreservationlist/Generalreservationlist',
              })
            }
          } else {
            wx.redirectTo({
              url: '/subpages/Generalreservationlist/Generalreservationlist',
            })
          }
        } else {
          wx.hideLoading()
          that.showTost(res.data.em);
        }
      },
      fail: function () {
        console.log("fail")
        wx.hideLoading()

      },
      complete: function () {
      }
    })

  },
  //支付接口
  payment: function () {
    var that = this;
    wx.showLoading({
      title: '加载中',
    })
    wx.request({
      url: app.globalData.requestUrl,
      data: {
        map: 'applet_order_pay',
        tid: that.data.info.trade.tid,
        money: that.data.info.trade.totalFee,
        plum_session_applet: app.globalData.plumSession

      },
      success: function (res) {
        console.log(res.data)
        if (res.data.ec == 200) {
          wx.hideLoading();

          wx.requestPayment({
            'appId': res.data.data.appId,
            'timeStamp': res.data.data.timeStamp,
            'nonceStr': res.data.data.nonceStr,
            'package': res.data.data.package,
            'signType': res.data.data.signType,
            'paySign': res.data.data.paySign,
            'success': function (res) {
              console.log(res);
              console.log("支付成功");
              that.setData({
                moneyVal: "",
                editDisable: true
              })
              // that.showTost("支付成功");
              // setTimeout(function () {
                wx.redirectTo({
                  url: '/subpages/Generalreservationlist/Generalreservationlist',
                })
              // }, 2000)
              // wx.navigateTo({
              //   url: '/subpages/successtip/successtip?money=' + data.money
              // })
            },
            'fail': function (res) {
              // wx.showModal({
              //   title: '',
              //   content: '支付失败',
              //   editDisable: false
              // });
              wx.hideLoading();
              that.showTost("支付失败");
              // wx.navigateTo({
              //   url: '/subpages/successtip/successtip?money=' + data.money
              // })
            }
          });
        } else {
          wx.hideLoading()
          that.showTost(res.data.em);
        }
      },
      fail: function () {
        wx.hideLoading()

      }
    })
  },

  showTost: function (toast) {
    wx.showToast({
      title: toast,
      image: "/images/hud_info.png",
      // icon: "loading",
      duration: 1000,
      mask: true
    })
  },
  // 监控数据改变
  dataChange: function (e) {
    var that = this;
    var remarkExtra = that.data.remarkExtra;
    var id = e.currentTarget.dataset.id;
    var type = e.currentTarget.dataset.type;
    var curVal = e.detail.value;
    for (var i = 0; i < remarkExtra.length; i++) {
      if (remarkExtra[i].id == id) {
        if (remarkExtra[i].type == 'time' && remarkExtra[i].date) {
          console.log("日期时间必填");
          remarkExtra[i][type] = curVal;
          if (remarkExtra[i].dateval && remarkExtra[i].timeval) {
            remarkExtra[i].value = remarkExtra[i].dateval + ' ' + remarkExtra[i].timeval;
          }
        } else {
          remarkExtra[i].value = curVal;
        }
      }
    }
    that.setData({
      remarkExtra: remarkExtra
    })
    console.log(that.data.remarkExtra);
  },
  // 上传图片
  chooseSingleImage: function (e) {
    var that = this;
    var id = e.currentTarget.dataset.id;
    wx.showActionSheet({
      itemList: ['从相册中选择', '拍照'],
      itemColor: "#333",
      success: function (res) {
        if (!res.cancel) {
          if (res.tapIndex == 0) {
            that.chooseWxImage('album', id)
          } else if (res.tapIndex == 1) {
            that.chooseWxImage('camera', id)
          }
        }
      }
    })
  },
  // 预览图片
  peiviewImg: function (e) {
    var curimg = e.currentTarget.dataset.curimg;
    var imgs = e.currentTarget.dataset.imgs;
    wx.previewImage({
      current: curimg, // 当前显示图片的http链接
      urls: imgs // 需要预览的图片http链接列表
    })
  },
  //选择单图
  chooseWxImage: function (type, id) {
    var that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: [type],
      success: function (res) {
        console.log(res);
        var temPath = res.tempFilePaths[0];
        that.upload_file(temPath, id);
      }
    })
  },
  // 上传单图到服务器
  upload_file: function (temPath, id) {
    var that = this;
    var remarkExtra = that.data.remarkExtra;
    wx.showLoading({
      title: '上传中',
    })
    wx.uploadFile({
      url: app.globalData.requestUrl + '?&map=applet_img_upload',
      filePath: temPath,
      name: 'image',
      success: function (res) {
        var data = JSON.parse(res.data);
        var realpath = app.globalData.domin + data.data.path;
        if (data.ec == 200) {
          for (var i = 0; i < remarkExtra.length; i++) {
            if (remarkExtra[i].id == id) {
              remarkExtra[i].img = realpath;
              remarkExtra[i].value = data.data.path;
            }
          }
          that.setData({
            remarkExtra: remarkExtra
          })
          console.log(that.data.remarkExtra);
        } else {
          wx.showModal({
            title: '提示',
            content: data.em,
            showCancel: false
          });
        }
      },
      complete: function () {
        wx.hideLoading();
      }
    });
  },
})